package com.ns.attendance.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Han
 */
public class DaysUtil {
	private final static List<String> ADDTIONALDAYS = new ArrayList<String>();
	
	static{
		try {
			String days = LoadConfig.getValue("days.additional");
			ADDTIONALDAYS.addAll(Arrays.asList(days.split(",")));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @return
	 */
	public static boolean isHoliday(Calendar calendar){
		try {
			String date = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			if((dayOfWeek == Calendar.SUNDAY  || dayOfWeek == Calendar.SATURDAY) && !ADDTIONALDAYS.contains(date)){
				//周六周日，并且不在例外中
				return true;
			}else if(dayOfWeek >Calendar.SUNDAY && dayOfWeek < Calendar.SATURDAY && ADDTIONALDAYS.contains(date)){
				//周一到周五，并且在例外中
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
	
	public static boolean isWorkDay(Calendar calendar){
		try {
			String date = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			if((dayOfWeek == Calendar.SUNDAY  || dayOfWeek == Calendar.SATURDAY) && ADDTIONALDAYS.contains(date)){
				//周六周日，并且在例外中
				return true;
			}else if(dayOfWeek >Calendar.SUNDAY && dayOfWeek < Calendar.SATURDAY && !ADDTIONALDAYS.contains(date)){
				//周一到周五，并且不在例外中
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
	
	public static Date getPreviousDay() {
		Calendar calendar = Calendar.getInstance();
		while(true){
			calendar.add(Calendar.DATE, -1);
			if(isWorkDay(calendar)){
				break;
			}else{
				continue;
			}
		}

		return calendar.getTime();
	}
	
	
	public static String getFirstDayOfMonthStr(int offset){
		Calendar firstDay = Calendar.getInstance();
		firstDay.add(Calendar.MONTH, offset);
		firstDay.set(Calendar.DAY_OF_MONTH, 1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(firstDay.getTime());
	}
	public static String getLastDayOfMonthStr(int offset){
		Calendar lastDay = Calendar.getInstance();
		lastDay.add(Calendar.MONTH, offset);
		lastDay.set(Calendar.DAY_OF_MONTH, lastDay.getActualMaximum(Calendar.DAY_OF_MONTH));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(lastDay.getTime());
	}
}
